#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/1
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :EC12_Past1MonAddedCnts_2D
# @Software  :PyCharm

'''eof
name:企业近1个月新增信贷笔数
code:EC12_Past1MonAddedCnts_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', 'None']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def nullCheck(str):
    if str not in null_type_list:
        return True
    else:
        return False

def EC10_UpaidLoanBal_2D():
    data = EC_DSJ_2D.get('data')
    factor1 = []
    factor2 = []
    ## 借贷账户信息 EDA [1..1]
    EDA = getTable(data, 'EDA', 1, 1)
    if EDA == [{}] or EDA == 0:
        factor1.append(0)
    else:
        ## 借贷账户信息单元 ED01 [0..*]
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}] or ED01 == 0:
            factor1.append(0)
        else:
            for i in ED01:
                ## 未结清借贷交易汇总信息段 EB02A [1..1]
                ED01A = getTable(i, 'ED01A', 1, 0)
                if ED01A == [{}] or ED01A == 0:
                    pass
                else:
                    #账户活动状态
                    ED01AD01 = ED01A[0].get('ED01AD01')
                    #开立日期
                    ED01AR01 = ED01A[0].get('ED01AR01')
                    if ED01AD01 not in null_type_list and ED01AR01 not in null_type_list:
                        time_ = dateFormat(ED01AR01)
                        if time_ in null_type_list:
                            pass
                        else:
                            time = time_.strftime("%Y%m%d")
                            if ED01AD01 == '1' and (datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=30)).strftime("%Y%m%d") <= time < datetime.datetime.now().strftime("%Y%m%d"):
                                factor1.append(1)
                            else:
                                pass

    ## 担保账户信息  EDB [1..1]
    EDB = getTable(data, 'EDB', 1, 1)
    if EDB == [{}] or EDB == 0:
        factor2.append(0)
    else:
        ## 担保账户信息明细单元 ED04 [0..*]
        ED04 = getTable(EDB[0], 'ED04', 0, 1)
        if ED04 == [{}] or ED04 == 0:
            factor2.append(0)
        else:
            for i in ED04:
                ## 在保责任信息段 ED04B [1..1]
                ED04B = getTable(i, 'ED04B', 1, 0)
                ED04A = getTable(i, 'ED04A', 1, 0)
                if ED04B == [{}] or ED04B == 0:
                    pass
                elif ED04A == [{}] or ED04A == 0:
                    pass
                else:
                    #账户活动状态
                    ED04BD01 = ED04B[0].get('ED04BD01')
                    #开立日期
                    ED04AR01 = ED04A[0].get('ED04AR01')
                    if ED04BD01 not in null_type_list and ED04AR01 not in null_type_list:
                        time_ = dateFormat(ED04AR01)
                        if time_ in null_type_list:
                            pass
                        else:
                            time = time_.strftime("%Y%m%d")
                            if ED04BD01 == '1' and (datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=30)).strftime("%Y%m%d") <= time < datetime.datetime.now().strftime("%Y%m%d"):
                                factor2.append(1)
                            else:
                                pass
    if len(factor1) == 0 and len(factor2) == 0:
        return 0
    elif list(set(factor1 + factor2))[0] == 0:
        return u'缺失值'
    else:
        res = len(factor1) + len(factor2)
        return res









if __name__ == '__main__':

    import json
    file_obj = open(r'C:\Users\john\Desktop\samples\EC_DSJ_2D.json', 'r')
    content = file_obj.read()
    EC_DSJ_2D = json.loads(content, strict=False)
    aa = EC10_UpaidLoanBal_2D()
    print(aa)

result = EC10_UpaidLoanBal_2D()